import java.util.HashMap;
import java.util.Map;

public class LRUCache {
    static class DLinkNode {
        public int key;
        public int value;
        public DLinkNode prev;
        public DLinkNode next;
        public DLinkNode() {};
        public DLinkNode(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }

    Map<Integer, DLinkNode> map;
    DLinkNode head, tail;
    int capacity, size;
    public LRUCache(int capacity) {
        map = new HashMap<>();
        head = new DLinkNode();
        tail = new DLinkNode();
        head.next = tail;
        tail.prev = head;
        this.capacity = capacity;
    }

    public int get(int key) {
        DLinkNode node = map.get(key);
        if (node == null) return -1;
        removeNode(node);
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkNode node = map.get(key);
        if (node == null) {
            node = new DLinkNode(key, value);
            map.put(key, node);
            moveToHead(node);
            this.size++;
            if (size > capacity) {
                removeNode(tail.prev);
                map.remove(tail.prev.key);
                this.size--;
            }
        }else {
            node.value = value;
            moveToHead(node);
        }
    }

    private void removeNode(DLinkNode node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
    }

    private void moveToHead(DLinkNode node) {
        node.next = head.next;
        head.next.prev = node;
        node.prev = head;
        head.next = node;
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(2);
        cache.put(1, 1);
        cache.put(2, 2);
        System.out.println(cache.get(1));
        cache.put(3, 3);
        System.out.println(cache.get(2));
        cache.put(4, 4);
        System.out.println(cache.get(1));
        System.out.println(cache.get(3));
        System.out.println(cache.get(4));
    }
}
